package com.yanxinim.cn.store;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.yanxinim.cn.AppConfig;
import com.yanxinim.cn.R;
import com.yanxinim.cn.luo.activity.ClickUtils;
import com.yanxinim.cn.store.bean.CartInfo;
import com.yanxinim.cn.store.bean.OrderGoodsInfo;
import com.yanxinim.cn.store.bean.StoreAddressInfo;
import com.yanxinim.cn.ui.base.BaseActivity;
import com.yanxinim.cn.util.JsonTool;
import com.yanxinim.cn.util.ToastUtil;
import com.yanxinim.cn.view.LoadingDialog;
import com.yanxinim.cn.view.TipDialog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class StoreOrderCommitActivity extends BaseActivity {

    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_user_phone)
    TextView tvUserPhone;
    @BindView(R.id.tv_user_address)
    TextView tvUserAddress;
    @BindView(R.id.rl_address)
    RelativeLayout rlAddress;
    @BindView(R.id.rv_goods_data)
    RecyclerView rvGoodsData;
    @BindView(R.id.scroll_view)
    NestedScrollView scrollView;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_goods_total)
    TextView tvGoodsTotal;
    @BindView(R.id.tv_goods_address_fee)
    TextView tvGoodsAddressFee;
    @BindView(R.id.tv_goods_discount_fee)
    TextView tvGoodsDiscountFee;
    @BindView(R.id.tv_tag)
    TextView tvTag;
    @BindView(R.id.tv_order_total)
    TextView tvOrderTotal;
    @BindView(R.id.tv_order_commit)
    TextView tvOrderCommit;
    @BindView(R.id.radio_ali_pay)
    RadioButton radioAliPay;
    @BindView(R.id.radio_wechat_pay)
    RadioButton radioWechatPay;
    @BindView(R.id.radio_wallet_pay)
    RadioButton radioWalletPay;
    @BindView(R.id.radio_group_pay)
    RadioGroup radioGroupPay;

    private List<Goods> goodsList = new ArrayList<>();
    private List<CartInfo> cartInfoList = new ArrayList<>();
    private StoreAddressInfo storeAddressInfo;
    private StoreGoodsAdapter goodsAdapter;
    double goodsTotal;
    double orderTotal;
    double addressFee;
    private double discountFee;
    private String payType;
    private LoadingDialog loadingDialog;
    private int type = 0;

    @SuppressLint("DefaultLocale")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_order_commit);
        ButterKnife.bind(this);
        loadingDialog = new LoadingDialog(this);
        type = getIntent().getIntExtra("type", 0);
        if (type == 1) {
            cartInfoList = (List<CartInfo>) getIntent().getSerializableExtra("goods");
            if (cartInfoList != null && cartInfoList.size() > 0) {
                for (CartInfo goods : cartInfoList) {
                    goodsTotal = Double.parseDouble(goods.getProductNum()) * Double.parseDouble(goods.getProductMoney()) + goodsTotal;
                    Goods goods1 = new Goods();
                    goods1.setId(goods.getProductId());
                    goods1.setCartAtime(goods.getCartAtime());
                    goods1.setProductLogo(goods.getProductLogo());
                    goods1.setProductMoney(goods.getProductMoney());
                    goods1.setProductNum(goods.getProductNum());
                    goods1.setProductName(goods.getProductName());
                    goods1.setProductWeight(goods.getProductWeigh());
                    goods1.setTotal(goods.getTotal());
                    goodsList.add(goods1);
                }
            }
        } else {
            goodsList = (List<Goods>) getIntent().getSerializableExtra("goods");
            for (Goods goods : goodsList) {
                if (TextUtils.isEmpty(goods.getProductOrgiMoney())){
                    goodsTotal = Double.parseDouble(goods.getProductNum()) * Double.parseDouble(goods.getProductMoney()) + goodsTotal;
                }else {
                    goodsTotal = Double.parseDouble(goods.getProductNum()) * Double.parseDouble(goods.getProductOrgiMoney()) + goodsTotal;
                }
            }
        }

        orderTotal = goodsTotal + addressFee - discountFee;
        rvGoodsData.setLayoutManager(new LinearLayoutManager(this));
        goodsAdapter = new StoreGoodsAdapter(this, goodsList, 2);
        goodsAdapter.setAdapterOnClickListener(new StoreGoodsAdapter.AdapterOnClickListener() {
            @Override
            public void onClick(int position, Goods data) {
                Intent intent = new Intent(StoreOrderCommitActivity.this, StoreGoodsDetailsActivity.class);
                intent.putExtra("productId", data.getId());
                startActivity(intent);
            }
        });
        rvGoodsData.setAdapter(goodsAdapter);

        payType = "wallet";
        radioGroupPay.check(R.id.radio_ali_pay);
        radioGroupPay.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radio_ali_pay:
                        payType = "ali";
                        break;
                    case R.id.radio_wechat_pay:
                        payType = "wechat";
                        break;
                    case R.id.radio_wallet_pay:
                        payType = "wallet";
                        break;
                }

            }
        });
        rlAddress.setOnClickListener(v -> {
            Intent intent = new Intent(mContext, StoreUserAddressActivity.class);
            intent.putExtra("type", 2);
            startActivityForResult(intent, 2021);
        });
        getAddressData();
        tvGoodsTotal.setText(String.format("￥%.2f", goodsTotal));
        tvOrderTotal.setText(String.format("￥%.2f", orderTotal));
        tvGoodsAddressFee.setText(String.format("￥%.2f", addressFee));
        tvGoodsDiscountFee.setText(String.format("￥%.2f", discountFee));

        ivBack.setOnClickListener(new ClickUtils.OnClickListener() {
            @Override
            public void onClick(View v, int type, int pos, int child) {
                finish();
            }
        });

        tvOrderCommit.setOnClickListener(new ClickUtils.OnClickListener() {
            @Override
            public void onClick(View v, int type, int pos, int child) {
                createOrder();
            }
        });

    }

    private void getAddressData() {
        Map<String, String> map = new HashMap<>();
        map.put("userId", getUser().getUserId());
        map.put("pageIndex", "0");
        map.put("pageSize", "2");
        HttpUtils.get().url(AppConfig.STORE_GET_ADDRESS)
                .params(map)
                .build().execute(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                JSONObject jsonObject = JSON.parseObject(result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (jsonObject.getInteger("resultCode") == 1) {
                            JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("data"));
                            List<StoreAddressInfo> storeAddressInfos = JsonTool.jsonToList(jsonObject1.getString("pageData"), StoreAddressInfo.class);
                            if (storeAddressInfos != null && storeAddressInfos.size() > 0) {
                                storeAddressInfo = storeAddressInfos.get(0);
                                tvUserName.setText(String.format("收货人：%s", storeAddressInfo.getUserName()));
                                tvUserPhone.setText(storeAddressInfo.getUserPhone());
                                tvUserAddress.setText(String.format("收货地址：%s%s", storeAddressInfo.getAddressText(), storeAddressInfo.getAddressCode()));
                            } else {
                                TipDialog tipDialog = new TipDialog(StoreOrderCommitActivity.this);
                                tipDialog.setmConfirmOnClickListener("没有收获地址，请先添加地址", new TipDialog.ConfirmOnClickListener() {
                                    @Override
                                    public void confirm() {
                                        Intent intent = new Intent(mContext, StoreUserAddressActivity.class);
                                        intent.putExtra("type", 2);
                                        startActivityForResult(intent, 2021);
                                    }
                                });
                                tipDialog.show();
                            }
                        }
                        Log.i("qin_store", result);
                    }
                });

            }
        });
    }


    private void createOrder() {
        if (loadingDialog != null)
            loadingDialog.show();
        Map<String, String> map = new HashMap<>();
        map.put("userId", getUser().getUserId());
        map.put("orderName", "安卓订单");
        map.put("orderMoney", String.valueOf(orderTotal));
        map.put("orderProductMoney", String.valueOf(goodsTotal));
        map.put("orderDiscountMoney", String.valueOf(discountFee));
        map.put("orderWlMoney", String.valueOf(addressFee));
        map.put("orderBill", "1");
        map.put("orderAtime", String.valueOf(System.currentTimeMillis()));
        map.put("userName", storeAddressInfo.getUserName());
        map.put("userPhone", storeAddressInfo.getUserPhone());
        map.put("userAddress", storeAddressInfo.getAddressText() + storeAddressInfo.getAddressCode());

        HttpUtils.post().url(AppConfig.STORE_CREATE_ORDER)
                .params(map)
                .build().execute(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                if (loadingDialog != null)
                    loadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                JSONObject jsonObject = JSON.parseObject(result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (jsonObject.getInteger("resultCode") == 1) {
                            String orderId = jsonObject.getString("data");
                            addGoods(orderId);
                        } else {
                            ToastUtil.showToast(StoreOrderCommitActivity.this, "创建订单失敗");
                            if (loadingDialog != null)
                                loadingDialog.dismiss();
                        }
                    }
                });

            }
        });
    }

    private void addGoods(String orderId) {
        List<OrderGoodsInfo> goodsList1 = new ArrayList<>();
        for (int i = 0; i < goodsList.size(); i++) {
            OrderGoodsInfo orderGoodsInfo = new OrderGoodsInfo();
            orderGoodsInfo.setOrderId(orderId);
            orderGoodsInfo.setProductId(goodsList.get(i).getId());
            orderGoodsInfo.setProductLogo(goodsList.get(i).getProductLogo());
            orderGoodsInfo.setProductMoney(goodsList.get(i).getProductMoney());
            orderGoodsInfo.setProductName(goodsList.get(i).getProductName());
            orderGoodsInfo.setProductNum(goodsList.get(i).getProductNum());
            orderGoodsInfo.setProductWeight(goodsList.get(i).getProductWeight());
            orderGoodsInfo.setProductOrgiMoney(goodsList.get(i).getProductOrgiMoney());
            goodsList1.add(orderGoodsInfo);
        }
        String json = JSON.toJSONString(goodsList1);
        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("productData", json);
        map.put("productNum", String.valueOf(goodsList.size()));

        HttpUtils.post().url(AppConfig.STORE_ORDER_ADD_GOODS)
                .params(map)
                .build().execute(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                if (loadingDialog != null)
                    loadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                JSONObject jsonObject = JSON.parseObject(result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (jsonObject.getInteger("resultCode") == 1) {
                            if (type == 1) {
                                delCart();
                            } else {
                                if (loadingDialog != null)
                                    loadingDialog.dismiss();
                                ToastUtil.showToast(StoreOrderCommitActivity.this, "创建订单成功");
                                finish();
                            }
                        } else {
                            if (loadingDialog != null)
                                loadingDialog.dismiss();
                            ToastUtil.showToast(StoreOrderCommitActivity.this, "创建订单失敗");
                        }
                    }
                });
            }
        });
    }


    private void cleanCart() {

        Map<String, String> map = new HashMap<>();
        map.put("userId", getUser().getUserId());

        HttpUtils.post().url(AppConfig.STORE_CLEAN_CART)
                .params(map)
                .build().execute(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                JSONObject jsonObject = JSON.parseObject(result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (jsonObject.getInteger("resultCode") == 1) {
                            if (loadingDialog != null)
                                loadingDialog.dismiss();
                            ToastUtil.showToast(StoreOrderCommitActivity.this, "创建订单成功");
                            finish();
                        } else {
                            if (loadingDialog != null)
                                loadingDialog.dismiss();
                            ToastUtil.showToast(StoreOrderCommitActivity.this, "创建订单失敗");
                        }
                    }
                });
            }
        });
    }

    private int cartDel = 0;

    private void delCart() {
        for (CartInfo cartInfo : cartInfoList) {
            delCartData(cartInfo);
        }
    }

    private void delCartData(CartInfo cartInfo) {

        Map<String, String> map = new HashMap<>();
        map.put("productId", cartInfo.getProductId());
        map.put("userId", getUser().getUserId());
        HttpUtils.get().url(AppConfig.STORE_DELETE_CART)
                .params(map)
                .build()
                .execute(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        cartDel++;
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        cartDel++;
                        if (cartDel == cartInfoList.size()) {
                            if (loadingDialog != null)
                                loadingDialog.dismiss();
                            finish();
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2021 && resultCode == 2021) {
            if (data != null) {
                storeAddressInfo = (StoreAddressInfo) data.getSerializableExtra("address");
                if (storeAddressInfo != null) {
                    tvUserName.setText(String.format("收货人：%s", storeAddressInfo.getUserName()));
                    tvUserPhone.setText(storeAddressInfo.getUserPhone());
                    tvUserAddress.setText(String.format("收货地址：%s%s", storeAddressInfo.getAddressText(), storeAddressInfo.getAddressCode()));
                }
            }
        }
    }
}
